<template>
  <div class="dashboard-container">
    <!-- 顶部筛选区 -->
    <el-card shadow="never" class="filter-card">
      <div class="filter-header">
        <h2>产品销量分析看板</h2>
        <div class="filter-actions">
          <el-button 
            type="primary" 
            size="small"
            @click="refreshData"
            :loading="loading">
            <i class="el-icon-refresh"></i> 刷新数据 
          </el-button>
        </div>
      </div>
    </el-card>
 
    <!-- 图表展示区（6:4比例） -->
    <el-row :gutter="20" class="chart-row">
      <!-- 左侧饼图（60%宽度） -->
      <el-col :span="14">
        <el-card shadow="never" class="chart-card">
          <div slot="header" class="chart-header">
            <span>产品销量TOP10（按PID）</span>
          </div>
          <div class="chart-container">
            <div ref="pieChart" style="width: 100%; height: 400px;"></div>
          </div>
        </el-card>
      </el-col>
      
      <!-- 右侧柱状图（40%宽度） -->
      <el-col :span="10">
        <el-card shadow="never" class="chart-card">
          <div slot="header" class="chart-header">
            <span>二手/定制销量对比</span>
          </div>
          <div class="chart-container">
            <div ref="barChart" style="width: 100%; height: 400px;"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>
 
    <!-- 数据表格区（保持原样） -->
    <el-card shadow="never" class="table-card">
      <div slot="header" class="table-header" >
        <span>产品销量详情</span>
        <div style="position: relative;left:87%;">
          <el-button 
            type="text" 
            @click="toggleConfigDisplay"
            icon="el-icon-s-operation">
            {{ showCustomConfig ? '隐藏配置详情' : '显示配置详情' }}
          </el-button>
          <el-button 
            type="primary" 
            size="small"
            @click="exportExcel"
            >
            <el-icon><Download /></el-icon>
            导出Excel 
          </el-button>
        </div>
      </div>
      
      <el-table 
        :data="productStats"
        v-loading="loading"
        border 
        stripe 
        highlight-current-row 
        style="width: 100%"
        class="stats-table">
        <el-table-column 
          prop="rank"
          label="排名"
          width="80"
          align="center"
          fixed>
          <template #default="{row}">
            <el-tag :type="getRankTagType(row.rank)"  effect="dark">
              {{ row.rank  }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column 
          prop="pid"
          label="产品ID"
          width="120"
          align="center">
        </el-table-column>
        <el-table-column 
          prop="name"
          label="产品名称"
          min-width="150"
          sortable>
          <template #default="{row}">
            <div class="product-name">
              {{ row.name  }}
              <el-tag 
                v-if="row.customize  === 1" 
                size="mini" 
                type="warning">
                定制 
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column 
          label="配置"
          width="180"
          align="center">
          <template #default="{row}">
            <div class="config-tags">
              <el-tag size="mini" :type="row.sidefork  === 0 ? 'primary' : 'success'">
                {{ row.sidefork  === 0 ? '二面叉' : '四面叉' }}
              </el-tag>
              <el-tag size="mini">
                {{ row.panel_leg  === 0 ? '原木板条' : '多层胶合板' }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column 
          prop="psq"
          label="销量(件)"
          width="120"
          align="center"
          sortable>
          <template #default="{row}">
            <el-tag :type="getSalesTagType(row.psq)"> 
              {{ row.psq  | formatNumber }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column 
          label="定制配置"
          width="200"
          v-if="showCustomConfig">
          <template #default="{row}">
            <div v-if="row.customize  === 1" class="custom-config">
              <div v-if="row.sidefork  === 0">
                <el-tag v-if="row.t_bottomlayer === 1" size="mini">底部拉秤</el-tag>
                <el-tag size="mini">{{ row.t_leglayout === 1 ? '三条腿' : '四条腿' }}</el-tag>
                <el-tag v-if="row.tf_boardwing  > 0" size="mini">板翼{{row.tf_boardwing}}cm</el-tag> 
              </div>
              <div v-else>
                <el-tag size="mini">结构{{ row.f_structure }}</el-tag>
                <el-tag size="mini">垫块{{row.f_blockheight}}cm</el-tag>
              </div>
            </div>
            <span v-else>-</span>
          </template>
        </el-table-column>
      </el-table>
 
      <div class="pagination-container">
        <el-pagination 
          background 
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>
 
<script>
import { use } from 'echarts/core'
import { PieChart, BarChart } from 'echarts/charts'
import { GridComponent, TooltipComponent, LegendComponent } from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import * as echarts from 'echarts'
import { product_StatsAPI } from '@/api/api'
import * as XLSX from 'xlsx'

use([PieChart, BarChart, GridComponent, TooltipComponent, LegendComponent, CanvasRenderer])
export default {
  name: 'ProductStatsRank',
  filters: {
    formatNumber(value) {
      return Number(value).toLocaleString()
    }
  },
  data() {
    return {
      productStats: [],
      loading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      lastCursor: null,
      isNextPage: true,
      showCustomConfig: false,
      pieChart: null,
      barChart: null 
    }
  },
  mounted() {
    this.initCharts() 
    this.fetchData() 
  },
  beforeDestroy() {
    if (this.pieChart)  {
      this.pieChart.dispose() 
    }
    if (this.barChart)  {
      this.barChart.dispose() 
    }
    window.removeEventListener('resize',  this.resizeCharts) 
  },
  methods: {
    initCharts() {
      this.pieChart  = echarts.init(this.$refs.pieChart) 
      this.barChart  = echarts.init(this.$refs.barChart) 
      window.addEventListener('resize',  this.resizeCharts) 
    },
    resizeCharts() {
      this.pieChart?.resize() 
      this.barChart?.resize() 
    },
    getRankTagType(rank) {
      if (rank <= 3) return 'danger'
      if (rank <= 6) return 'warning'
      return 'success'
    },
    getSalesTagType(sales) {
      sales = Number(sales)
      if (sales > 1000) return 'danger'
      if (sales > 500) return 'warning'
      return 'success'
    },
    async fetchData() {
      this.loading  = true 
      try {
        const params = {
          limit: this.pageSize, 
          direction: this.isNextPage  ? 'next' : 'prev',
          cursor: this.lastCursor  
        }
        
        const res = await product_StatsAPI(params)
        this.productStats  = (res.data?.data  || []).map((item, index) => ({
          ...item,
          sidefork: Number(item.sidefork), 
          panel_leg: Number(item.panel_leg), 
          customize: Number(item.customize), 
          t_bottomlayer: Number(item.t_bottomlayer || 0),
          t_leglayout: Number(item.t_leglayout || 0),
          tf_boardwing: Number(item.tf_boardwing  || 0),
          f_structure: item.f_structure || 'N',
          f_blockheight: Number(item.f_blockheight || 0),
          rank: (this.currentPage  - 1) * this.pageSize  + index + 1 
        }))
        
        this.total  = res.data?.total  || 0 
        this.lastCursor  = res.data?.nextCursor  
        
        this.updateCharts() 
        
      } catch (error) {
        this.$message.error(' 数据加载失败: ' + (error.message  || error))
      } finally {
        this.loading  = false 
      }
    },
    updateCharts() {
      // 1. 饼图数据 - 按PID的销量TOP10 
      const top10Products = [...this.productStats] 
        .sort((a, b) => b.psq  - a.psq) 
        .slice(0, 10)
        .map(item => ({
          name: `PID:${item.pid}`, 
          value: item.psq, 
          item: item 
        }))
 
      // 2. 柱状图数据 - 按定制/二手分类 
      const customSales = this.productStats  
        .filter(item => item.customize  === 1)
        .reduce((sum, item) => sum + item.psq,  0)
      
      const secondhandSales = this.productStats  
        .filter(item => item.customize  !== 1)
        .reduce((sum, item) => sum + item.psq,  0)
 
      // 更新饼图 
      this.pieChart.setOption({ 
        tooltip: {
          trigger: 'item',
          formatter: params => {
            const data = params.data  
            return `
              <strong>${data.name}</strong><br/> 
              名称: ${data.item.name}<br/> 
              销量: ${data.value} 件<br/>
              类型: ${data.item.customize  === 1 ? '定制' : '二手'}
            `
          }
        },
        legend: {
          orient: 'vertical',
          right: 10,
          top: 'center',
          data: top10Products.map(item  => item.name) 
        },
        series: [{
          name: '销量TOP10',
          type: 'pie',
          radius: ['40%', '70%'],
          data: top10Products,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2 
          },
          label: {
            formatter: '{b}\n{c}件'
          }
        }]
      })
 
      // 更新柱状图 
      this.barChart.setOption({ 
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'shadow' },
          formatter: '{b}<br/>销量: {c}件'
        },
        xAxis: {
          type: 'category',
          data: ['二手产品', '定制产品']
        },
        yAxis: {
          type: 'value',
          name: '销量(件)'
        },
        series: [{
          name: '销量',
          type: 'bar',
          barWidth: '40%',
          data: [secondhandSales, customSales],
          itemStyle: {
            color: params => params.dataIndex  === 0 ? '#409EFF' : '#E6A23C'
          },
          label: {
            show: true,
            position: 'top'
          }
        }]
      })
    },
    refreshData() {
      this.currentPage  = 1 
      this.lastCursor  = null 
      this.isNextPage  = true 
      this.fetchData() 
    },
    handleSizeChange(val) {
      this.pageSize  = val 
      this.refreshData() 
    },
    handleCurrentChange(val) {
      this.currentPage  = val 
      this.fetchData() 
    },
    toggleConfigDisplay() {
      this.showCustomConfig  = !this.showCustomConfig  
    },
    exportExcel() {
  this.exportLoading  = true; // 添加加载状态 
  try {
    // 准备数据（保持原有数据处理逻辑不变）
    const exportData = this.productStats.map(item  => ({
      '排名': item.rank, 
      '产品ID': item.pid, 
      '产品名称': item.name, 
      '产品类型': item.customize  === 1 ? '定制' : '二手',
      '叉车类型': item.sidefork  === 0 ? '二面叉' : '四面叉',
      '面板类型': item.panel_leg  === 0 ? '原木板条' : '多层胶合板',
      '销量(件)': item.psq, 
      '配置详情': this.getConfigDetail(item) 
    }));
 
    // 创建工作簿 
    const wb = XLSX.utils.book_new(); 
    const ws = XLSX.utils.json_to_sheet(exportData); 
    
    // 设置列宽（优化Excel显示效果）
    ws['!cols'] = [
      { wch: 8 },   // 排名 
      { wch: 12 },  // 产品ID 
      { wch: 25 },  // 产品名称 
      { wch: 10 },  // 产品类型 
      { wch: 10 },  // 叉车类型 
      { wch: 15 },  // 面板类型 
      { wch: 10 },  // 销量 
      { wch: 30 }   // 配置详情 
    ];
 
    // 添加工作表 
    XLSX.utils.book_append_sheet(wb,  ws, "产品销量数据");
 
    // 生成带时间的文件名（格式：产品销量_yyyymmddhhmm.xlsx ）
    const now = new Date();
    const timeString = [
      now.getFullYear(), 
      String(now.getMonth()  + 1).padStart(2, '0'),
      String(now.getDate()).padStart(2,  '0'),
      String(now.getHours()).padStart(2,  '0'),
      String(now.getMinutes()).padStart(2,  '0')
    ].join('');
    const fileName = `产品销量_${timeString}.xlsx`;
 
    // 导出Excel文件 
    XLSX.writeFile(wb,  fileName);
    
    this.$message.success('Excel 导出成功');
  } catch (error) {
    console.error(' 导出失败:', error);
    this.$message.error(' 导出失败: ' + error.message); 
  } finally {
    this.exportLoading  = false;
  }
},
    getConfigDetail(item) {
      if (item.customize  !== 1) return '标准配置'
      
      if (item.sidefork  === 0) {
        let parts = []
        if (item.t_bottomlayer === 1) parts.push(' 底部拉秤')
        parts.push(`${item.t_leglayout} 条腿`)
        if (item.tf_boardwing  > 0) parts.push(` 板翼${item.tf_boardwing}cm`) 
        return parts.join('+') 
      } else {
        return `结构${item.f_structure}+垫块${item.f_blockheight}cm`
      }
    }
  }
}
</script>
 
<style scoped>
/* 布局调整 */
.chart-row .el-col-14 {
  width: 60%;
}
.chart-row .el-col-10 {
  width: 40%;
}
 
/* 保持原有样式 */
.dashboard-container {
  padding: 20px;
  background-color: #f5f7fa;
}
.filter-card {
  margin-bottom: 20px;
}
.chart-card {
  margin-bottom: 20px;
}
.table-card {
  margin-top: 20px;
}
.stats-table {
  margin-top: 15px;
}
.product-name {
  display: flex;
  align-items: center;
}
.config-tags {
  display: flex;
  justify-content: center;
  gap: 4px;
  flex-wrap: wrap;
}
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
.el-tag {
  font-weight: bold;
}
 
/* 响应式调整 */
@media (max-width: 768px) {
  .chart-row .el-col-14,
  .chart-row .el-col-10 {
    width: 100%;
  }
}
</style>